package com.mouse.magent.common.util;

import sun.nio.cs.Surrogate;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class PropUtil {
    public static HashMap<String, String> propMap = null;
    public static String baseResource = "/application.properties";
    public static String baseFile = "config.txt";

    private static void init(String baseResource) {
        if (propMap != null) return;
        propMap = new HashMap<>();
        InputStream inputStream = null;
        InputStream inputStream2 = null;
        try {
            inputStream = Surrogate.Generator.class.getResourceAsStream(baseResource);
            ResourceBundle resource = new PropertyResourceBundle(inputStream);
            Enumeration<String> allConfig = resource.getKeys();
            while (allConfig.hasMoreElements()) {
                String key = allConfig.nextElement();
                String value1 = resource.getString(key);
                String value2 = new String(value1.getBytes("iso-8859-1"), "utf-8");
                propMap.put(key, value2);
            }
            if(new File(baseFile).exists()){
                inputStream2 = new FileInputStream(new File(baseFile));
                resource = new PropertyResourceBundle(inputStream2);
                allConfig = resource.getKeys();
                while (allConfig.hasMoreElements()) {
                    String key = allConfig.nextElement();
                    String value1 = resource.getString(key);
                    propMap.put(key, value1);
                }
            }
        } catch (Exception e) {
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream2 != null) {
                try {
                    inputStream2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String getValue(String baseResource, String key, String defaultValue) {
        init(baseResource);
        String value = propMap.get(key);
        return value != null ? value : defaultValue;
    }

    public static String getValue(String key, String defaultValue) {
        return getValue(baseResource, key, defaultValue);
    }
}
